<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>轨迹展示</title>
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            height: 100vh;
            height: 100dvh; /* 动态视口高度，适应地址栏变化 */
            overflow: hidden;
            position: fixed;
            width: 100%;
            top: 0;
            left: 0;
        }
        .header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 2000;
            margin-bottom: 0;
            padding: 8px 12px;
            background-color: #f0f0f0;
            border-radius: 0;
            min-height: 60px;
            box-sizing: border-box;
        }
        .room-input {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-bottom: 5px;
            flex-wrap: wrap;
        }
        .room-input input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .room-input button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .room-input button:hover {
            background-color: #0056b3;
        }
        .room-input button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .auto-refresh-group {
            display: flex;
            gap: 5px;
            align-items: center;
        }
        .refresh-btn {
            padding: 6px 12px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s;
        }
        .refresh-btn:hover {
            background-color: #218838;
            transform: translateY(-1px);
        }
        .refresh-btn.active {
            background-color: #ffc107;
            color: #212529;
            box-shadow: 0 2px 8px rgba(255, 193, 7, 0.3);
        }
        .refresh-btn.stop-btn {
            background-color: #dc3545;
        }
        .refresh-btn.stop-btn:hover {
            background-color: #c82333;
        }
        .content {
            position: relative;
            height: calc(100vh - 85px);
            height: calc(100dvh - 85px); /* 动态视口高度减去header高度 */
            min-height: 400px;
            margin-top: 85px; /* 为header留出空间，增加5px避免按钮遮挡 */
        }
        .sidebar {
            position: absolute;
            top: 15px;
            left: 5px;
            width: 120px;
            max-height: calc(100vh - 80px);
            background-color: transparent;
            backdrop-filter: none;
            border-radius: 0;
            padding: 6px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: none;
            border: none;
        }
        .sidebar h4 {
            margin: 0 0 4px 0;
            color: #333;
            font-size: 14px;
            text-align: left;
            padding-bottom: 2px;
            border-bottom: 1px solid rgba(0,0,0,0.1);
        }
        .show-all-btn {
            width: 100%;
            padding: 6px 8px;
            margin-bottom: 8px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            font-weight: bold;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .show-all-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
        .show-all-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .show-all-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .person-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .person-item {
            padding: 4px 6px;
            margin-bottom: 4px;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 4px;
            cursor: pointer;
            border: 1px solid transparent;
            transition: all 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .person-item:hover {
            background-color: rgba(227, 242, 253, 0.95);
            border-color: #2196f3;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(33, 150, 243, 0.2);
        }
        .person-item.active {
            background-color: rgba(187, 222, 251, 0.95);
            border-color: #1976d2;
            box-shadow: 0 2px 12px rgba(25, 118, 210, 0.3);
        }
        .person-item.recent {
            background-color: rgba(200, 255, 200, 0.9) !important;
            border-color: #4caf50;
            box-shadow: 0 2px 8px rgba(76, 175, 80, 0.2);
        }
        .person-item.recent:hover {
            background-color: rgba(180, 255, 180, 0.95) !important;
            border-color: #388e3c;
            box-shadow: 0 3px 12px rgba(56, 142, 60, 0.3);
        }
        .person-item.recent.active {
            background-color: rgba(165, 245, 165, 0.95) !important;
            border-color: #2e7d32;
            box-shadow: 0 3px 15px rgba(46, 125, 50, 0.4);
        }
        .person-name {
            font-weight: bold;
            color: #333;
            font-size: 14px;
        }
        .person-time {
            font-size: 11px;
            color: #666;
            white-space: nowrap;
        }
        #map {
            width: 100%;
            height: 100%;
            border-radius: 0;
            box-shadow: none;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 20px;
        }
        .error {
            color: #dc3545;
            background-color: #f8d7da;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
        }

                .success {
            color: #155724;
            background-color: #d4edda;
            padding: 6px 10px;
            border-radius: 4px;
            margin-top: 5px;
            font-size: 12px;
            border-left: 3px solid #28a745;
            position: relative;
            z-index: 10;
        }

        /* 日期选择器样式 */
        .date-selector {
            display: flex;
            gap: 5px;
            align-items: center;
            flex-wrap: wrap;
            margin-top: 5px;
        }
        .date-btn {
            padding: 4px 8px;
            background-color: #6c757d;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 11px;
            transition: all 0.2s;
        }
        .date-btn:hover {
            background-color: #5a6268;
            transform: translateY(-1px);
        }
        .date-btn.active {
            background-color: #007bff;
            box-shadow: 0 2px 6px rgba(0, 123, 255, 0.3);
        }

        /* 轨迹控制面板 */
        .track-controls {
            display: flex;
            gap: 5px;
            align-items: center;
            margin-top: 5px;
            flex-wrap: wrap;
        }
        .track-btn {
            padding: 4px 8px;
            background-color: #17a2b8;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 11px;
            transition: all 0.2s;
        }
        .track-btn:hover {
            background-color: #138496;
            transform: translateY(-1px);
        }
        .track-btn.active {
            background-color: #28a745;
            box-shadow: 0 2px 6px rgba(40, 167, 69, 0.3);
        }

        /* 自定义标记样式 */
        .custom-marker {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 2px solid white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            color: white;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            box-shadow: 0 2px 6px rgba(0,0,0,0.3);
        }

        /* 起点标记 */
        .start-marker {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border: 3px solid #28a745;
            background-color: #28a745;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: bold;
            color: white;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            box-shadow: 0 2px 8px rgba(40, 167, 69, 0.4);
        }

        /* 终点标记 */
        .end-marker {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border: 3px solid #dc3545;
            background-color: #dc3545;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: bold;
            color: white;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            box-shadow: 0 2px 8px rgba(220, 53, 69, 0.4);
        }

        /* 姓名标签样式 */
        .name-label {
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            white-space: nowrap;
            margin-top: 2px;
            text-align: center;
        }

        /* 轨迹时间标签样式 */
        .track-time-label {
            background-color: rgba(0, 0, 0, 0.6);
            color: white;
            padding: 2px 4px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: normal;
            white-space: nowrap;
            text-align: center;
            pointer-events: none;
            box-shadow: 0 1px 3px rgba(0,0,0,0.3);
        }

        /* 轨迹点击提示 */
        .track-click-popup {
            background-color: rgba(255, 255, 255, 0.95);
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 11px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.2);
        }


        /* 折叠按钮 */
        .sidebar-toggle {
            width: 100%;
            height: 28px;
            background-color: rgba(248, 249, 250, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.2s;
            margin-bottom: 8px;
            font-size: 12px;
            color: #666;
        }
        .sidebar-toggle:hover {
            background-color: rgba(33, 150, 243, 0.1);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .sidebar-toggle::before {
            content: '👥';
            font-size: 16px;
        }
        .sidebar.collapsed {
            transform: translateX(-100%);
            opacity: 0;
            pointer-events: none;
        }

        /* 显示按钮 - 当侧边栏隐藏时显示 */
        .show-sidebar-btn {
            position: absolute;
            top: 15px;
            left: 5px;
            width: 40px;
            height: 28px;
            background-color: rgba(248, 249, 250, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 4px;
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.2s;
            z-index: 1001;
            font-size: 16px;
            color: #666;
        }
        .show-sidebar-btn:hover {
            background-color: rgba(33, 150, 243, 0.1);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .show-sidebar-btn::before {
            content: '👥';
        }
        .sidebar.collapsed + .show-sidebar-btn {
            display: flex;
        }

        @media (max-width: 768px) {
            .content {
                height: calc(100vh - 85px);
                min-height: 350px;
            }
            .sidebar {
                width: 100px;
                max-width: 320px;
                max-height: 40%;
            }
            .sidebar h4 {
                font-size: 14px;
            }
            .show-all-btn {
                font-size: 11px;
                padding: 5px 6px;
            }
            .person-item {
                padding: 6px 10px;
                flex-direction: column;
                align-items: flex-start;
                gap: 2px;
            }
            .person-name {
                font-size: 13px;
            }
            .person-time {
                font-size: 10px;
            }
        }

        @media (max-width: 480px) {
            .content {
                height: calc(100vh - 85px);
                min-height: 300px;
            }
            .sidebar {
                top: 10px;
                left: 5px;
                width: 80px;
                max-height: calc(100vh - 80px);
                padding: 4px;
            }
            .show-sidebar-btn {
                top: 10px;
                left: 5px;
                width: 35px;
                height: 28px;
                font-size: 16px;
            }
            .room-input {
                gap: 8px;
            }
            .room-input input {
                font-size: 13px;
                padding: 6px 10px;
            }
            .room-input button {
                font-size: 13px;
                padding: 6px 12px;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <div class="room-input">
        <input type="text" id="roomInput" placeholder="请输入房间名称" />
        <button id="searchBtn" onclick="searchTrack()">查询轨迹</button>
    </div>
    <div class="date-selector">
        <span style="font-size: 12px; color: #666;">选择日期:</span>
        <button class="date-btn active" data-day="today" onclick="selectDay('today')">今天</button>
        <button class="date-btn" data-day="today-1" onclick="selectDay('today-1')">昨天</button>
        <button class="date-btn" data-day="today-2" onclick="selectDay('today-2')">前天</button>
        <button class="date-btn" data-day="today-3" onclick="selectDay('today-3')">3天前</button>
        <button class="date-btn" data-day="today-4" onclick="selectDay('today-4')">4天前</button>
        <button class="date-btn" data-day="today-5" onclick="selectDay('today-5')">5天前</button>
        <button class="date-btn" data-day="today-6" onclick="selectDay('today-6')">6天前</button>
    </div>
    <div class="track-controls">
        <span style="font-size: 12px; color: #666;">轨迹显示:</span>
        <button class="track-btn active" id="showAllTracksBtn" onclick="toggleAllTracks()">显示全部轨迹</button>
        <button class="track-btn" id="optimizeBtn" onclick="toggleOptimization()">智能优化</button>
        <button class="track-btn active" id="timeLabelsBtn" onclick="toggleTimeLabels()">时间标签</button>
    </div>
    <div id="status">请输入房间名称并选择日期查询轨迹信息</div>
    <div id="mapStatus" style="display: none;">
        <span id="mapStatusText"></span>
        <button id="retryMapBtn" onclick="retryMapLoad()" style="margin-left: 10px; padding: 4px 8px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;">重试地图</button>
    </div>
</div>

<div class="content">
    <div class="sidebar" id="sidebar">
        <div class="sidebar-toggle" id="sidebarToggle" onclick="toggleSidebar()"></div>
        <h4>轨迹列表 (<span id="personCount">0</span>)</h4>
        <button id="showAllBtn" class="show-all-btn" onclick="showAllTracks()" style="display: none;">
            🛤️ 显示全部轨迹
        </button>
        <ul id="personList" class="person-list">
            <li class="loading">暂无数据</li>
        </ul>
    </div>
    <div class="show-sidebar-btn" id="showSidebarBtn" onclick="toggleSidebar()"></div>
    <div id="map"></div>
</div>

<!-- Leaflet JavaScript -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
    // 初始化地图
    var map = L.map('map').setView([39.9042, 116.4074], 10);

    // 尝试多个瓦片服务以解决CORS问题
    function initializeTileLayer() {
        const tileServices = [
            // 使用国内镜像，通常没有CORS问题
            {
                url: 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                attribution: '© 高德地图',
                subdomains: '1234',
                maxZoom: 18
            },
            // OpenStreetMap 德国镜像 - 通常支持CORS
            {
                url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png',
                attribution: '© OpenStreetMap contributors',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // CartoDB 瓦片服务 - 支持CORS
            {
                url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
                attribution: '© CartoDB, © OpenStreetMap contributors',
                subdomains: 'abcd',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // Stamen 地图服务 - 支持CORS
            {
                url: 'https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png',
                attribution: '© Stamen Design, © OpenStreetMap contributors',
                subdomains: 'abcd',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // ESRI 世界地图 - 支持CORS
            {
                url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
                attribution: '© Esri, © OpenStreetMap contributors',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // 原始 OpenStreetMap - 作为最后备选
            {
                url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                attribution: '© OpenStreetMap contributors',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            }
        ];

        let currentServiceIndex = 0;
        let currentTileLayer = null;

        function tryNextService() {
            if (currentServiceIndex >= tileServices.length) {
                console.error('所有瓦片服务都无法加载');
                const status = document.getElementById('status');
                status.textContent = '地图瓦片加载失败，可能是网络问题';
                status.className = 'error';
                return;
            }

            const service = tileServices[currentServiceIndex];
            console.log(`尝试瓦片服务 ${currentServiceIndex + 1}: ${service.url}`);

            // 移除之前的图层
            if (currentTileLayer) {
                map.removeLayer(currentTileLayer);
            }

            currentTileLayer = L.tileLayer(service.url, {
                attribution: service.attribution,
                maxZoom: service.maxZoom,
                subdomains: service.subdomains || 'abc',
                crossOrigin: service.crossOrigin || false,
                errorTileUrl: ''
            });

            let errorCount = 0;
            const maxErrors = 5; // 允许的最大错误数

            // 监听瓦片加载错误
            currentTileLayer.on('tileerror', function(error) {
                errorCount++;
                console.warn(`瓦片服务 ${currentServiceIndex + 1} 瓦片加载失败 (${errorCount}/${maxErrors}):`, error);

                if (errorCount >= maxErrors) {
                    console.warn(`瓦片服务 ${currentServiceIndex + 1} 错误过多，尝试下一个服务`);
                    currentServiceIndex++;
                    setTimeout(tryNextService, 1000); // 延迟1秒后尝试下一个服务
                }
            });

            // 监听瓦片加载成功
            currentTileLayer.on('tileload', function() {
                console.log(`瓦片服务 ${currentServiceIndex + 1} 加载成功`);
            });

            currentTileLayer.addTo(map);
        }

        // 开始尝试第一个服务
        tryNextService();
    }

    // 初始化瓦片图层
    initializeTileLayer();

    // 将缩放控件移到右下角
    map.zoomControl.setPosition('bottomright');

        // 全局变量
    var markers = [];
    var trackLines = [];
    var trackData = {};
    var currentActiveUser = null;
    var currentDay = 'today';

    // Mock数据开关 - 默认关闭，使用真实API
    var useMockData = false; // 暂时使用Mock数据测试

    // API配置
    var API_BASE_URL = 'http://locationshare.wangt.cc/nosso/quickreport/list';

    // 轨迹显示控制
    var showAllTracksEnabled = true;
    var optimizeMode = false;
    var showTimeLabels = true;

    // 创建轨迹点图标
    function createTrackIcon(name, index, isOptimized = false) {
        const iconStyles = [
            { bg: '#FF6B6B', emoji: '😊' },
            { bg: '#4ECDC4', emoji: '🌟' },
            { bg: '#45B7D1', emoji: '🎯' },
            { bg: '#96CEB4', emoji: '🚀' },
            { bg: '#FFEAA7', emoji: '💎' },
            { bg: '#DDA0DD', emoji: '🎨' },
            { bg: '#98D8C8', emoji: '🎪' },
            { bg: '#F7DC6F', emoji: '🎭' },
            { bg: '#BB8FCE', emoji: '🎸' },
            { bg: '#85C1E9', emoji: '🎲' }
        ];

        const style = iconStyles[index % iconStyles.length];
        const size = isOptimized ? 16 : 20;

        const iconHtml = `
            <div class="custom-marker" style="background-color: ${style.bg}; width: ${size}px; height: ${size}px; font-size: ${size-8}px;">
                ${style.emoji}
            </div>
        `;

        return L.divIcon({
            html: iconHtml,
            className: 'custom-div-icon',
            iconSize: [size, size],
            iconAnchor: [size/2, size/2],
            popupAnchor: [0, -size/2]
        });
    }

    // 创建起点图标
    function createStartIcon() {
        return L.divIcon({
            html: '<div class="start-marker">🚩</div>',
            className: 'custom-div-icon',
            iconSize: [24, 24],
            iconAnchor: [12, 12],
            popupAnchor: [0, -12]
        });
    }

    // 创建终点图标
    function createEndIcon() {
        return L.divIcon({
            html: '<div class="end-marker">🏁</div>',
            className: 'custom-div-icon',
            iconSize: [24, 24],
            iconAnchor: [12, 12],
            popupAnchor: [0, -12]
        });
    }

    // 创建时间标签图标
    function createTimeIcon(timeString) {
        const timeText = formatTime(timeString);
        return L.divIcon({
            html: `<div class="track-time-label">${timeText}</div>`,
            className: 'custom-div-icon',
            iconSize: [40, 16],
            iconAnchor: [20, 24], // 调整锚点，让时间标签显示在点位上方
            popupAnchor: [0, -24]
        });
    }

    // 创建带姓名标签的图标
    function createNamedIcon(name, index) {
        const iconStyles = [
            { bg: '#FF6B6B', emoji: '😊' },
            { bg: '#4ECDC4', emoji: '🌟' },
            { bg: '#45B7D1', emoji: '🎯' },
            { bg: '#96CEB4', emoji: '🚀' },
            { bg: '#FFEAA7', emoji: '💎' },
            { bg: '#DDA0DD', emoji: '🎨' },
            { bg: '#98D8C8', emoji: '🎪' },
            { bg: '#F7DC6F', emoji: '🎭' },
            { bg: '#BB8FCE', emoji: '🎸' },
            { bg: '#85C1E9', emoji: '🎲' }
        ];

        const style = iconStyles[index % iconStyles.length];

        const iconHtml = `
            <div style="display: flex; flex-direction: column; align-items: center;">
                <div class="custom-marker" style="background-color: ${style.bg}">
                    ${style.emoji}
                </div>
                <div class="name-label">${name}</div>
            </div>
        `;

        return L.divIcon({
            html: iconHtml,
            className: 'custom-div-icon',
            iconSize: [60, 50],
            iconAnchor: [30, 25],
            popupAnchor: [0, -25]
        });
    }

    // 坐标转换函数：WGS84转GCJ02（GPS坐标转火星坐标）
    function wgs84ToGcj02(lng, lat) {
        const a = 6378245.0;
        const ee = 0.00669342162296594323;

        if (outOfChina(lng, lat)) {
            return [lng, lat];
        }

        let dLat = transformLat(lng - 105.0, lat - 35.0);
        let dLng = transformLng(lng - 105.0, lat - 35.0);
        const radLat = lat / 180.0 * Math.PI;
        let magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        const sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
        dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI);
        const mgLat = lat + dLat;
        const mgLng = lng + dLng;
        return [mgLng, mgLat];
    }

    function transformLat(lng, lat) {
        let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * Math.PI) + 320 * Math.sin(lat * Math.PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    function transformLng(lng, lat) {
        let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * Math.PI) + 300.0 * Math.sin(lng / 30.0 * Math.PI)) * 2.0 / 3.0;
        return ret;
    }

    function outOfChina(lng, lat) {
        return (lng < 72.004 || lng > 137.8347) || (lat < 0.8293 || lat > 55.8271);
    }

    // 判断是否为最近位置（10分钟内）
    function isRecentLocation(timeString) {
        const now = new Date();
        const targetTime = new Date(timeString);
        const diffMs = now - targetTime;
        const diffMinutes = Math.floor(diffMs / (1000 * 60));

        return diffMinutes <= 10; // 10分钟内认为是最近位置
    }

    // 获取日期文本
    function getDayText(dayType) {
        const dayTexts = {
            'today': '今天',
            'today-1': '昨天',
            'today-2': '前天',
            'today-3': '3天前',
            'today-4': '4天前',
            'today-5': '5天前',
            'today-6': '6天前'
        };
        return dayTexts[dayType] || dayType;
    }

    // 选择日期
    function selectDay(dayType) {
        currentDay = dayType;

        // 更新按钮状态
        document.querySelectorAll('.date-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-day="${dayType}"]`).classList.add('active');

        // 如果已有房间输入，自动重新查询
        const room = document.getElementById('roomInput').value.trim();
        if (room) {
            searchTrack();
        }
    }

    // 轨迹数据优化算法
    function optimizeTrackData(locations, maxPoints = 50) {
        if (locations.length <= maxPoints) {
            return locations;
        }

        const optimized = [locations[0]]; // 保留起点
        const step = Math.floor(locations.length / (maxPoints - 2));

        for (let i = step; i < locations.length - 1; i += step) {
            // 检查是否与前一个点距离足够远
            const prev = optimized[optimized.length - 1];
            const curr = locations[i];
            const distance = calculateDistance(prev.latitude, prev.longitude, curr.latitude, curr.longitude);

            if (distance > 0.01) { // 距离大于10米才保留
                optimized.push(curr);
            }
        }

        optimized.push(locations[locations.length - 1]); // 保留终点
        return optimized;
    }

    // 计算两点间距离（公里）
    function calculateDistance(lat1, lon1, lat2, lon2) {
        const R = 6371; // 地球半径（公里）
        const dLat = (lat2 - lat1) * Math.PI / 180;
        const dLon = (lon2 - lon1) * Math.PI / 180;
        const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                  Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                  Math.sin(dLon/2) * Math.sin(dLon/2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c;
    }

    // 根据时间进度获取颜色（从蓝色到红色的渐变）
    function getTimeBasedColor(progress) {
        // progress: 0-1，0表示最早时间，1表示最晚时间

        // 使用分段颜色，让渐变更明显
        if (progress <= 0.2) {
            // 0-20%: 深蓝色到蓝色
            const localProgress = progress / 0.2;
            const hue = 240 - (localProgress * 20); // 240° -> 220°
            return `hsl(${hue}, 90%, 45%)`;
        } else if (progress <= 0.4) {
            // 20-40%: 蓝色到青色
            const localProgress = (progress - 0.2) / 0.2;
            const hue = 220 - (localProgress * 40); // 220° -> 180°
            return `hsl(${hue}, 85%, 50%)`;
        } else if (progress <= 0.6) {
            // 40-60%: 青色到绿色
            const localProgress = (progress - 0.4) / 0.2;
            const hue = 180 - (localProgress * 60); // 180° -> 120°
            return `hsl(${hue}, 80%, 50%)`;
        } else if (progress <= 0.8) {
            // 60-80%: 绿色到黄色
            const localProgress = (progress - 0.6) / 0.2;
            const hue = 120 - (localProgress * 60); // 120° -> 60°
            return `hsl(${hue}, 85%, 55%)`;
        } else {
            // 80-100%: 黄色到红色
            const localProgress = (progress - 0.8) / 0.2;
            const hue = 60 - (localProgress * 60); // 60° -> 0°
            return `hsl(${hue}, 90%, 60%)`;
        }
    }

    // 创建时间渐变轨迹线
    function createTimeGradientTrack(tracks, userName) {
        if (tracks.length < 2) return [];

        const trackLines = [];

        // 获取时间范围
        const startTime = new Date(tracks[0].ctime).getTime();
        const endTime = new Date(tracks[tracks.length - 1].ctime).getTime();
        const timeRange = endTime - startTime;

        console.log(`[渐变色] 用户 ${userName} 轨迹时间范围:`, {
            startTime: new Date(startTime).toLocaleString(),
            endTime: new Date(endTime).toLocaleString(),
            timeRange: timeRange,
            trackCount: tracks.length
        });

        // 如果时间范围太小（小于1分钟），使用索引进度代替时间进度
        const useIndexProgress = timeRange < 60000; // 小于1分钟

        if (useIndexProgress) {
            console.log(`[渐变色] 时间范围过小(${timeRange}ms)，使用索引进度`);
        }

        // 为每两个相邻点创建一条线段
        for (let i = 0; i < tracks.length - 1; i++) {
            const currentTrack = tracks[i];
            const nextTrack = tracks[i + 1];

            // 计算当前线段的进度
            let progress;
            if (useIndexProgress) {
                // 使用索引进度：第一条线段为0，最后一条线段为1
                progress = tracks.length > 2 ? i / (tracks.length - 2) : 0;
            } else {
                // 使用时间进度
                const currentTime = new Date(currentTrack.ctime).getTime();
                progress = timeRange > 0 ? (currentTime - startTime) / timeRange : 0;
            }

            // 确保progress在0-1范围内
            progress = Math.max(0, Math.min(1, progress));

            // 转换坐标
            const [currentLng, currentLat] = wgs84ToGcj02(currentTrack.longitude, currentTrack.latitude);
            const [nextLng, nextLat] = wgs84ToGcj02(nextTrack.longitude, nextTrack.latitude);

            // 获取颜色
            const color = getTimeBasedColor(progress);

            console.log(`[渐变色] 线段 ${i+1}/${tracks.length-1}, 进度: ${progress.toFixed(3)}, 颜色: ${color}`);

            // 创建线段
            const segment = L.polyline([
                [currentLat, currentLng],
                [nextLat, nextLng]
            ], {
                color: color,
                weight: 4,
                opacity: 0.8,
                smoothFactor: 1
            }).addTo(map);

            // 为线段添加点击事件
            segment.on('click', function(e) {
                const popup = L.popup()
                    .setLatLng(e.latlng)
                    .setContent(`
                        <div class="track-click-popup">
                            <b>${userName}</b><br>
                            时间: ${formatTime(currentTrack.ctime)} - ${formatTime(nextTrack.ctime)}<br>
                            进度: ${(progress * 100).toFixed(1)}%<br>
                            <small>颜色表示时间早晚：🔵蓝色(早) → 🔴红色(晚)</small>
                        </div>
                    `)
                    .openOn(map);
            });

            trackLines.push(segment);
        }

        console.log(`[渐变色] 用户 ${userName} 创建了 ${trackLines.length} 条渐变线段`);
        return trackLines;
    }

    // 格式化时间为简短格式
    function formatTime(timeString) {
        const date = new Date(timeString);
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 选择时间标签点位 - 显示所有点位的时间
    function selectTimePoints(tracks, maxPoints = 999) {
        if (tracks.length <= 2) return [];

        // 排除起点和终点，从中间选择
        const middleTracks = tracks.slice(1, -1);
        console.log(`显示所有时间标签，总共${middleTracks.length}个中间点位`);

        // 直接返回所有中间点位，不做任何过滤
        return middleTracks;
    }



    // 搜索轨迹信息
    async function searchTrack() {
        const roomInput = document.getElementById('roomInput');
        const searchBtn = document.getElementById('searchBtn');
        const status = document.getElementById('status');

        const room = roomInput.value.trim();
        if (!room) {
            status.textContent = '请输入房间名称';
            status.className = 'error';
            return;
        }

        // 设置加载状态
        searchBtn.disabled = true;
        searchBtn.textContent = '查询中...';
        status.textContent = `正在查询${getDayText(currentDay)}的轨迹信息...`;
        status.className = '';

        try {
            let result;

            // 保存搜索历史
            saveSearchHistory(room);

            if (useMockData) {
                // 使用Mock数据
                console.log('使用Mock数据模式');

                // 模拟API延迟
                await new Promise(resolve => setTimeout(resolve, 800));

                // 从mock_list.json加载数据
                const response = await fetch('/quick_report/mock_list.json');
                result = await response.json();
            } else {
                // 使用真实API
                console.log('使用真实API模式，请求URL:', `${API_BASE_URL}?room=${encodeURIComponent(room)}&dayType=${currentDay}`);

                const response = await fetch(`${API_BASE_URL}?room=${encodeURIComponent(room)}&dayType=${currentDay}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    signal: AbortSignal.timeout(15000) // 15秒超时
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                result = await response.json();
                console.log('API返回数据:', result);
            }

            // 处理返回结果
            if (result.code === 0 && result.data && Object.keys(result.data).length > 0) {
                trackData = result.data;
                updateTrackList();
                updateTrackMap();

                const totalPoints = Object.values(trackData).reduce((sum, tracks) => sum + tracks.length, 0);
                status.textContent = `成功获取 ${Object.keys(trackData).length} 个用户的轨迹，共 ${totalPoints} 个位置点`;
                status.className = 'success';

                // 3秒后自动清除成功提示
                setTimeout(() => {
                    status.textContent = '';
                    status.className = '';
                }, 3000);
            } else {
                status.textContent = result.msg || '未找到轨迹信息';
                status.className = 'error';
                clearTrackData();

                // 3秒后自动清除错误提示
                setTimeout(() => {
                    status.textContent = '';
                    status.className = '';
                }, 3000);
            }
        } catch (error) {
            console.error('API调用失败:', error);

            if (error.name === 'TimeoutError') {
                status.textContent = '请求超时，请检查网络连接';
            } else if (error.name === 'TypeError' && error.message.includes('fetch')) {
                status.textContent = '网络连接失败，请检查网络状态';
            } else {
                status.textContent = `请求失败: ${error.message}`;
            }

            status.className = 'error';
            clearTrackData();

            // 3秒后自动清除错误提示
            setTimeout(() => {
                status.textContent = '';
                status.className = '';
            }, 3000);
        } finally {
            searchBtn.disabled = false;
            searchBtn.textContent = '查询轨迹';
        }
    }

    // 更新轨迹列表
    function updateTrackList() {
        const personList = document.getElementById('personList');
        const personCount = document.getElementById('personCount');
        const showAllBtn = document.getElementById('showAllBtn');

        const userNames = Object.keys(trackData);
        personCount.textContent = userNames.length;

        if (userNames.length === 0) {
            personList.innerHTML = '<li class="loading">暂无数据</li>';
            showAllBtn.style.display = 'none';
            return;
        }

        showAllBtn.style.display = 'block';

        personList.innerHTML = '';
        userNames.forEach((userName, index) => {
            const userTracks = trackData[userName];
            const trackCount = userTracks.length;
            const firstTime = userTracks[0]?.ctime;
            const lastTime = userTracks[trackCount - 1]?.ctime;

            const li = document.createElement('li');
            li.className = 'person-item';
            li.setAttribute('data-user', userName);

            li.innerHTML = `
                <div class="person-name">${userName}</div>
                <div class="person-time">${trackCount}个点位<br>${formatTime(firstTime)}-${formatTime(lastTime)}</div>
            `;

            li.addEventListener('click', function() {
                selectUserTrack(userName);
            });

            personList.appendChild(li);
        });
    }

    // 更新轨迹地图
    function updateTrackMap() {
        clearTrackMap();

        if (Object.keys(trackData).length === 0) return;

        const userNames = Object.keys(trackData);

        userNames.forEach((userName, userIndex) => {
            const userTracks = trackData[userName];
            if (userTracks.length === 0) return;

            // 根据优化模式决定是否简化轨迹
            const displayTracks = optimizeMode ? optimizeTrackData(userTracks) : userTracks;

            // 创建时间渐变轨迹线
            const timeGradientLines = createTimeGradientTrack(displayTracks, userName);
            trackLines.push(...timeGradientLines);

            // 添加时间标签（显示所有点位）
            if (showTimeLabels) {
                const timePoints = selectTimePoints(displayTracks); // 显示所有时间标签
                timePoints.forEach(timePoint => {
                    const [timeLng, timeLat] = wgs84ToGcj02(timePoint.longitude, timePoint.latitude);
                    const timeMarker = L.marker([timeLat, timeLng], {
                        icon: createTimeIcon(timePoint.ctime),
                        zIndexOffset: -100 // 让时间标签显示在其他标记下方
                    }).addTo(map);
                    markers.push(timeMarker);
                });
            }

            // 添加起点和终点标记
            if (displayTracks.length > 0) {
                const startTrack = displayTracks[0];
                const endTrack = displayTracks[displayTracks.length - 1];

                const [startLng, startLat] = wgs84ToGcj02(startTrack.longitude, startTrack.latitude);
                const [endLng, endLat] = wgs84ToGcj02(endTrack.longitude, endTrack.latitude);

                // 起点
                const startMarker = L.marker([startLat, startLng], { icon: createStartIcon() })
                    .addTo(map)
                    .bindPopup(`<b>${userName} - 起点</b><br>时间: ${formatTime(startTrack.ctime)}`);
                markers.push(startMarker);

                // 终点（如果不是同一个点）
                if (displayTracks.length > 1) {
                    const endMarker = L.marker([endLat, endLng], { icon: createEndIcon() })
                        .addTo(map)
                        .bindPopup(`<b>${userName} - 终点</b><br>时间: ${formatTime(endTrack.ctime)}`);
                    markers.push(endMarker);
                }

                // 如果不是优化模式，添加中间点位
                if (!optimizeMode && displayTracks.length > 2) {
                    displayTracks.slice(1, -1).forEach((track, index) => {
                        const [lng, lat] = wgs84ToGcj02(track.longitude, track.latitude);
                        const marker = L.marker([lat, lng], {
                            icon: createTrackIcon(userName, userIndex, false)
                        })
                        .addTo(map)
                        .bindPopup(`<b>${userName}</b><br>时间: ${formatTime(track.ctime)}`);
                        markers.push(marker);
                    });
                }
            }
        });

        // 自动缩放地图
        if (trackLines.length > 0) {
            const group = new L.featureGroup([...trackLines, ...markers]);
            map.fitBounds(group.getBounds().pad(0.1));
        }
    }

    // 选择用户轨迹
    function selectUserTrack(userName) {
        // 更新列表选中状态
        const personItems = document.querySelectorAll('.person-item');
        personItems.forEach(item => item.classList.remove('active'));

        const selectedItem = document.querySelector(`[data-user="${userName}"]`);
        if (selectedItem) {
            selectedItem.classList.add('active');
        }

        currentActiveUser = userName;

        // 重新绘制地图，只显示选中用户的轨迹
        clearTrackMap();

        const userTracks = trackData[userName];
        if (userTracks && userTracks.length > 0) {
            const displayTracks = optimizeMode ? optimizeTrackData(userTracks) : userTracks;

            // 创建时间渐变轨迹线
            const timeGradientLines = createTimeGradientTrack(displayTracks, userName);
            trackLines.push(...timeGradientLines);

            // 添加时间标签（显示所有点位）
            if (showTimeLabels) {
                const timePoints = selectTimePoints(displayTracks); // 显示所有时间标签
                timePoints.forEach(timePoint => {
                    const [timeLng, timeLat] = wgs84ToGcj02(timePoint.longitude, timePoint.latitude);
                    const timeMarker = L.marker([timeLat, timeLng], {
                        icon: createTimeIcon(timePoint.ctime),
                        zIndexOffset: -100
                    }).addTo(map);
                    markers.push(timeMarker);
                });
            }

            // 添加起点和终点
            const startTrack = displayTracks[0];
            const endTrack = displayTracks[displayTracks.length - 1];

            const [startLng, startLat] = wgs84ToGcj02(startTrack.longitude, startTrack.latitude);
            const [endLng, endLat] = wgs84ToGcj02(endTrack.longitude, endTrack.latitude);

            const startMarker = L.marker([startLat, startLng], { icon: createStartIcon() })
                .addTo(map)
                .bindPopup(`<b>${userName} - 起点</b><br>时间: ${formatTime(startTrack.ctime)}`);
            markers.push(startMarker);

            if (displayTracks.length > 1) {
                const endMarker = L.marker([endLat, endLng], { icon: createEndIcon() })
                    .addTo(map)
                    .bindPopup(`<b>${userName} - 终点</b><br>时间: ${formatTime(endTrack.ctime)}`);
                markers.push(endMarker);
            }

            // 如果不是优化模式，添加中间点位
            if (!optimizeMode && displayTracks.length > 2) {
                displayTracks.slice(1, -1).forEach((track, index) => {
                    const [lng, lat] = wgs84ToGcj02(track.longitude, track.latitude);
                    const marker = L.marker([lat, lng], {
                        icon: createTrackIcon(userName, 0, false) // 使用统一的样式索引
                    })
                    .addTo(map)
                    .bindPopup(`<b>${userName}</b><br>时间: ${formatTime(track.ctime)}`);
                    markers.push(marker);
                });
            }

            // 缩放到轨迹
            const group = new L.featureGroup([...timeGradientLines, ...markers]);
            map.fitBounds(group.getBounds().pad(0.1));
        }
    }

    // 显示全部轨迹
    function showAllTracks() {
        if (Object.keys(trackData).length === 0) return;

        // 清除选中状态
        const personItems = document.querySelectorAll('.person-item');
        personItems.forEach(item => item.classList.remove('active'));

        currentActiveUser = null;

        // 重新显示所有轨迹
        updateTrackMap();
    }

    // 清除轨迹地图
    function clearTrackMap() {
        markers.forEach(marker => map.removeLayer(marker));
        trackLines.forEach(line => map.removeLayer(line));
        markers = [];
        trackLines = [];
    }

    // 清除轨迹数据
    function clearTrackData() {
        trackData = {};
        clearTrackMap();
        updateTrackList();
    }

    // 切换全部轨迹显示
    function toggleAllTracks() {
        showAllTracksEnabled = !showAllTracksEnabled;
        const btn = document.getElementById('showAllTracksBtn');

        if (showAllTracksEnabled) {
            btn.classList.add('active');
            btn.textContent = '显示全部轨迹';
            showAllTracks();
        } else {
            btn.classList.remove('active');
            btn.textContent = '隐藏轨迹';
            clearTrackMap();
        }
    }

    // 切换优化模式
    function toggleOptimization() {
        optimizeMode = !optimizeMode;
        const btn = document.getElementById('optimizeBtn');

        if (optimizeMode) {
            btn.classList.add('active');
            btn.textContent = '已优化';
        } else {
            btn.classList.remove('active');
            btn.textContent = '智能优化';
        }

        // 重新绘制地图
        if (currentActiveUser) {
            selectUserTrack(currentActiveUser);
        } else {
            updateTrackMap();
        }
    }

    // 切换时间标签显示
    function toggleTimeLabels() {
        showTimeLabels = !showTimeLabels;
        const btn = document.getElementById('timeLabelsBtn');

        if (showTimeLabels) {
            btn.classList.add('active');
            btn.textContent = '时间标签';
            addTimeLabelsToMap();
        } else {
            btn.classList.remove('active');
            btn.textContent = '隐藏时间';
            // 移除时间标签
            removeTimeLabelsFromMap();
        }
    }

    // 添加时间标签到地图
    function addTimeLabelsToMap() {
        if (currentActiveUser) {
            // 单用户模式
            const userTracks = trackData[currentActiveUser];
            if (userTracks && userTracks.length > 0) {
                const displayTracks = optimizeMode ? optimizeTrackData(userTracks) : userTracks;
                const timePoints = selectTimePoints(displayTracks);
                timePoints.forEach(timePoint => {
                    const [timeLng, timeLat] = wgs84ToGcj02(timePoint.longitude, timePoint.latitude);
                    const timeMarker = L.marker([timeLat, timeLng], {
                        icon: createTimeIcon(timePoint.ctime),
                        zIndexOffset: -100
                    }).addTo(map);
                    markers.push(timeMarker);
                });
            }
        } else {
            // 多用户模式
            const userNames = Object.keys(trackData);
            userNames.forEach((userName, userIndex) => {
                const userTracks = trackData[userName];
                if (userTracks.length === 0) return;

                const displayTracks = optimizeMode ? optimizeTrackData(userTracks) : userTracks;
                const timePoints = selectTimePoints(displayTracks);
                timePoints.forEach(timePoint => {
                    const [timeLng, timeLat] = wgs84ToGcj02(timePoint.longitude, timePoint.latitude);
                    const timeMarker = L.marker([timeLat, timeLng], {
                        icon: createTimeIcon(timePoint.ctime),
                        zIndexOffset: -100
                    }).addTo(map);
                    markers.push(timeMarker);
                });
            });
        }
    }

    // 从地图移除时间标签
    function removeTimeLabelsFromMap() {
        // 只移除时间标签，保留其他标记
        const timeMarkers = markers.filter(marker => {
            return marker.options.zIndexOffset === -100;
        });

        timeMarkers.forEach(marker => {
            map.removeLayer(marker);
            const index = markers.indexOf(marker);
            if (index > -1) {
                markers.splice(index, 1);
            }
        });
    }




    // 搜索历史管理
    const SEARCH_HISTORY_KEY = 'quickreport_search_history';
    const MAX_HISTORY_ITEMS = 10;

    // 加载搜索历史
    function loadSearchHistory() {
        try {
            const history = localStorage.getItem(SEARCH_HISTORY_KEY);
            return history ? JSON.parse(history) : [];
        } catch (e) {
            console.warn('读取搜索历史失败:', e);
            return [];
        }
    }

    // 保存搜索历史
    function saveSearchHistory(searchTerm) {
        if (!searchTerm || searchTerm.trim() === '') return;

        try {
            let history = loadSearchHistory();
            const term = searchTerm.trim();

            // 移除已存在的相同项
            history = history.filter(item => item !== term);

            // 添加到开头
            history.unshift(term);

            // 限制历史记录数量
            if (history.length > MAX_HISTORY_ITEMS) {
                history = history.slice(0, MAX_HISTORY_ITEMS);
            }

            localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
        } catch (e) {
            console.warn('保存搜索历史失败:', e);
        }
    }

    // 显示搜索建议
    function showSearchSuggestions(inputElement) {
        const history = loadSearchHistory();
        if (history.length === 0) return;

        // 移除现有的建议列表
        const existingSuggestions = document.querySelector('.search-suggestions');
        if (existingSuggestions) {
            existingSuggestions.remove();
        }

        // 创建建议列表
        const suggestions = document.createElement('div');
        suggestions.className = 'search-suggestions';
        suggestions.style.cssText = `
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 4px 4px;
            max-height: 150px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        `;

        // 添加建议项
        history.forEach(term => {
            const item = document.createElement('div');
            item.className = 'suggestion-item';
            item.textContent = term;
            item.style.cssText = `
                padding: 8px 12px;
                cursor: pointer;
                font-size: 14px;
                border-bottom: 1px solid #f0f0f0;
                transition: background-color 0.2s;
            `;

            item.addEventListener('mouseenter', function() {
                this.style.backgroundColor = '#f8f9fa';
            });

            item.addEventListener('mouseleave', function() {
                this.style.backgroundColor = 'white';
            });

            item.addEventListener('click', function() {
                inputElement.value = term;
                suggestions.remove();
                searchTrack();
            });

            suggestions.appendChild(item);
        });

        // 添加到输入框的父元素
        const parent = inputElement.parentElement;
        parent.style.position = 'relative';
        parent.appendChild(suggestions);

        // 点击其他地方关闭建议
        setTimeout(() => {
            document.addEventListener('click', function closeSuggestions(e) {
                if (!suggestions.contains(e.target) && e.target !== inputElement) {
                    suggestions.remove();
                    document.removeEventListener('click', closeSuggestions);
                }
            });
        }, 100);
    }

    // 初始化搜索输入框
    function initSearchInput() {
        const roomInput = document.getElementById('roomInput');

        // 输入框获得焦点时显示建议
        roomInput.addEventListener('focus', function() {
            if (this.value.trim() === '') {
                showSearchSuggestions(this);
            }
        });

        // 输入内容时更新建议
        roomInput.addEventListener('input', function() {
            if (this.value.trim() === '') {
                showSearchSuggestions(this);
            } else {
                // 移除现有的建议列表
                const existingSuggestions = document.querySelector('.search-suggestions');
                if (existingSuggestions) {
                    existingSuggestions.remove();
                }
            }
        });

        // 回车键搜索
        roomInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                // 移除建议列表
                const suggestions = document.querySelector('.search-suggestions');
                if (suggestions) {
                    suggestions.remove();
                }
                searchTrack();
            }
        });

        // 搜索按钮点击事件
        const searchBtn = document.getElementById('searchBtn');
        searchBtn.addEventListener('click', function() {
            // 移除建议列表
            const suggestions = document.querySelector('.search-suggestions');
            if (suggestions) {
                suggestions.remove();
            }
        });
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        initSearchInput();
        // 页面加载时自动填充最近的搜索词
        autoFillLastSearch();
    });

    // 自动填充最近的搜索词
    function autoFillLastSearch() {
        try {
            const history = loadSearchHistory();
            if (history && history.length > 0) {
                const roomInput = document.getElementById('roomInput');
                roomInput.value = history[0];
            }
        } catch (e) {
            console.warn('自动填充最近搜索词失败:', e);
        }
    }

    // 切换侧边栏显示/隐藏
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        sidebar.classList.toggle('collapsed');
    }

    // 重试地图加载
    function retryMapLoad() {
        console.log('重试加载地图瓦片...');
        const mapStatus = document.getElementById('mapStatus');
        mapStatus.style.display = 'none';

        // 重新初始化瓦片图层
        initializeTileLayer();
    }

    // 可选：添加点击事件获取坐标（调试用）
    map.on('click', function(e) {
        console.log('点击坐标: ' + e.latlng.lat + ', ' + e.latlng.lng);
    });

    // 监听视口变化，防止地址栏隐藏时布局错乱
    function handleViewportChange() {
        // 强制重新计算地图大小
        setTimeout(() => {
            if (map) {
                map.invalidateSize();
            }
        }, 100);
    }

    // 监听视口大小变化
    window.addEventListener('resize', handleViewportChange);

    // 监听方向变化
    window.addEventListener('orientationchange', () => {
        setTimeout(handleViewportChange, 500);
    });

    // 监听页面可见性变化（地址栏显示/隐藏时触发）
    document.addEventListener('visibilitychange', handleViewportChange);
</script>
</body>
</html>
